package com.train.member.service.Impl;

import cn.hutool.core.collection.CollUtil;
import com.train.common.execption.BusinessException;
import com.train.common.execption.BusinessExceptionEnum;
import com.train.common.until.SnowUtil;
import com.train.member.domain.Member;
import com.train.member.domain.MemberExample;
import com.train.member.mapper.MemberMapper;
import com.train.member.req.MemberLoginReq;
import com.train.member.req.MemberRegisterReq;
import com.train.member.resp.MemberLoginResp;
import com.train.member.service.MemberService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.jiawa.train.common.util.JwtUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MemberServiceImpl implements MemberService {
    @Resource
    private MemberMapper memberMapper;

    @Override
    public long Register(MemberRegisterReq memberRegisterReq) {

        //设置查询条件
        MemberExample memberExample = new MemberExample();
        memberExample.createCriteria().andMobileEqualTo(memberRegisterReq.getMobile());

        List<Member> members = memberMapper.selectByExample(memberExample);
        if (CollUtil.isNotEmpty(members)){
            //手机号已经存在
            throw new BusinessException(BusinessExceptionEnum.MEMBER_MOBILE_EXIST);
        }

        Member member = new Member();
        member.setId(SnowUtil.getSnowflakeNextId());
        member.setMobile(memberRegisterReq.getMobile());
        return memberMapper.insertSelective(member);
    }

    @Override
    public MemberLoginResp login(MemberLoginReq memberLoginReq) {
        String code = memberLoginReq.getCode();
        String mobile = memberLoginReq.getMobile();

        //验证验证码是否正确(应该是从Redis中取出来进行对比) String cacheCode = ""
        if (!code.equals("8888")){
            throw new BusinessException(BusinessExceptionEnum.CHECK_CODE_ERROR);
        }

        //检查手机号是否注册过
        MemberExample memberExample = new MemberExample();
        memberExample.createCriteria().andMobileEqualTo(mobile);
        List<Member> members = memberMapper.selectByExample(memberExample);
        Member member = null;

        if (CollUtil.isEmpty(members)){
            member = new Member();
            member.setId(SnowUtil.getSnowflakeNextId());
            member.setMobile(mobile);
            memberMapper.insertSelective(member);
        }

        //生成jwt，设置返回数据
        member = members.get(0);
        String jwt  = JwtUtil.createToken(member.getId(),mobile);

        MemberLoginResp memberLoginResp = new MemberLoginResp();
        memberLoginResp.setId(member.getId());
        memberLoginResp.setMobile(mobile);
        memberLoginResp.setToken(jwt);

        return memberLoginResp;
    }


}
